// src/mock/bannerMock.js
import Mock from "mockjs";

// 轮播图列表数据
const { bannerList } = Mock.mock({
    "bannerList": [
        { id: "id-1", title: "Banner 1", url: "assets/banner/1.png" },
        { id: "id-2", title: "Banner 2", url: "assets/banner/2.png" },
        { id: "id-3", title: "Banner 3", url: "assets/banner/3.png" },
        { id: "id-4", title: "Banner 4", url: "assets/banner/4.png" },
        { id: "id-5", title: "Banner 5", url: "assets/banner/5.png" }
    ]
});

// 获取轮播图列表接口
Mock.mock("/banner/list", "post", (config) => {
    const req = JSON.parse(config.body);
    return {
        code: 1,
        message: "获取轮播图列表成功",
        data: {
            bannerList: bannerList.slice((req.count - 1) * req.pageSize, req.count * req.pageSize),
            length: bannerList.length
        }
    };
});

// 添加新的轮播图
Mock.mock("/banner/add", "post", (config) => {
    // 由于 Mock.js 无法直接解析 FormData，我们需要手动从 FormData 中提取数据
    const formData = new FormData();
    const req = new URLSearchParams(config.body); // 模拟从请求中解析出表单字段

    const title = req.get('title');
    const url = req.get('url'); // 假设在前端上传时，后端返回了一个图片的 URL

    // 添加新的轮播图到 bannerList
    bannerList.push({
        id: `id-${Math.random().toString(36).substr(2, 9)}`,
        title: title,
        url: url,
    });

    return {
        code: 200,
        message: '添加数据成功',
    };
});


// 删除轮播图接口
Mock.mock("/banner/delete", "post", (config) => {
    const req = JSON.parse(config.body);
    const index = bannerList.findIndex(item => item.id === req.id);

    if (index !== -1) {
        bannerList.splice(index, 1);
        return {
            code: 200,
            message: '数据删除成功',
        };
    } else {
        return {
            code: 404,
            message: '未找到该数据，删除失败',
        };
    }
});

// 编辑轮播图接口
Mock.mock("/banner/edit", "post", (config) => {
    const req = JSON.parse(config.body)

    const res = {
        code: 200,
        message: '修改数据失败'
    }

    for (let i = 0; i < bannerList.length; i++) {
        if (bannerList[i].proid == req.proid) {
            bannerList[i] = req
            res.message = '数据修改成功'
            break
        }
    }

    return res
});
